<?php
namespace app\admin\controller;

use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\PhpWord;

class WordTable{
public function table(){
// 假设你已经有了一个数据源，例如从数据库查询到的数据数组
$dataSource = [
    ['one', 'two', 'three'],
    ['Row1', 'Data1', 'Data2'],
    ['Row2', 'Data3', 'Data4'],
    // ... 更多行数据
];
 
// 创建一个新的Word文档
$phpWord = new PhpWord();
 
// 添加一个新的空白页面
$section = $phpWord->addSection();
 
// 遍历数据源创建表格
foreach ($dataSource as $row) {
    // 添加一行到表格
    $table = $section->addTable();
    foreach ($row as $cell) {
        $table->addRow()->addCell(900)->addText($cell);
    }
}
 
// 保存Word文档
$objWriter = IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('static/myStorageFile/table.docx');
 
// 如果需要直接输出到浏览器
// header('Content-Type: application/octet-stream');
// header('Content-Disposition: attachment;filename="' . $filename . '"');
// $objWriter->save('php://output');
}
}